package com.delivery.www.servlet;

import com.alibaba.fastjson.JSON;
import com.delivery.www.po.Dish;
import com.delivery.www.service.ServiceImpl.DishServiceImpl;
import com.delivery.www.util.PageSupport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author 12970
 */
public class DishServlet extends BaseServlet {
    DishServiceImpl dishService = new DishServiceImpl();

    /**
     * 修改菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void modifyDish(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        int dishId = Integer.parseInt(req.getParameter("dishId"));
        String field = req.getParameter("field");
        String value = req.getParameter("value");
        boolean b = dishService.judgeField(dishId, value, storeId, field);
        if (b) {
            writer.print("ok");
        } else {
            writer.print("error");
        }
    }

    /**
     * 删除菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void deleteDish(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        int dishId = Integer.parseInt(req.getParameter("dishId"));
        boolean b = dishService.deleteDish(dishId, storeId);
        if (b) {
            writer.print("ok");
        } else {
            writer.print("error");
        }
    }

    /**
     * 用户获取菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void userSelectDish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        String dishName = req.getParameter("dishName");
        String currentPageNo = req.getParameter("currentPageNo");
        boolean flag = false;
        int currentPage = 1;
        int pageSize = 3;
        if (dishName == null) {
            dishName = "";
        }
        if (!"".equals(currentPageNo) && currentPageNo != null) {
            currentPage = Integer.parseInt(currentPageNo);
        }
        List<Dish> dishes = dishService.getDish(storeId, dishName, currentPage, pageSize);
        int dishCount = dishService.getDishCount(storeId, dishName);
        int totalPageCount;
        if (dishCount % pageSize == 0) {
            totalPageCount = (dishCount / pageSize);
        } else {
            totalPageCount = (dishCount / pageSize) + 1;
        }
        PageSupport.setCurrentPageNo(currentPage);
        PageSupport.setPageSize(pageSize);
        PageSupport.setTotalCount(dishCount);
        PageSupport.setTotalPageCount(totalPageCount);
        if (currentPage < 1) {
            currentPage = 1;
        } else if (currentPage > totalPageCount) {
            currentPage = totalPageCount;
        }
        req.setAttribute("dishName", dishName);
        req.setAttribute("dishes", dishes);
        req.setAttribute("currentPageNo", currentPage);
        req.setAttribute("pageSize", pageSize);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("flag", flag);
        req.getRequestDispatcher("User/UserDishPage.jsp").forward(req, resp);
    }

    /**
     * 游客获取菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void selectDish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        String dishName = req.getParameter("dishName");
        String currentPageNo = req.getParameter("currentPageNo");
        boolean flag = false;
        int currentPage = 1;
        int pageSize = 3;
        if (dishName == null) {
            dishName = "";
        }
        if (!"".equals(currentPageNo) && currentPageNo != null) {
            currentPage = Integer.parseInt(currentPageNo);
        }
        List<Dish> dishes = dishService.getDish(storeId, dishName, currentPage, pageSize);
        int dishCount = dishService.getDishCount(storeId, dishName);
        int totalPageCount;
        if (dishCount % pageSize == 0) {
            totalPageCount = (dishCount / pageSize);
        } else {
            totalPageCount = (dishCount / pageSize) + 1;
        }
        PageSupport.setCurrentPageNo(currentPage);
        PageSupport.setPageSize(pageSize);
        PageSupport.setTotalCount(dishCount);
        PageSupport.setTotalPageCount(totalPageCount);
        if (currentPage < 1) {
            currentPage = 1;
        } else if (currentPage > totalPageCount) {
            currentPage = totalPageCount;
        }
        req.setAttribute("dishName", dishName);
        req.setAttribute("dishes", dishes);
        req.setAttribute("currentPageNo", currentPage);
        req.setAttribute("pageSize", pageSize);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("flag", flag);
        req.getRequestDispatcher("DishPage.jsp").forward(req, resp);
    }

    /**
     * 商家获取菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void sellerSelectDish(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int storeId = Integer.parseInt(req.getParameter("storeId"));
        boolean flag = false;
        List<Dish> dishes = dishService.getDish(storeId);
        req.setAttribute("dishes", dishes);
        req.setAttribute("flag", flag);
        req.getRequestDispatcher("/Seller/SellerDishPage.jsp").forward(req, resp);
    }

    /**
     * 获取一个菜品
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void selectOne(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        int dishId = Integer.parseInt(req.getParameter("dishId"));
        Dish dish = dishService.getOneDish(dishId);
        writer.print(JSON.toJSONString(dish));
    }

    /**
     * 增加菜品
     *
     * @param req  请求
     * @param resp 响应
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) {
        //上传到服务器存放路径
        String uploadFilePath = "D:/code/Java/delivery-system-pro/photo";
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建工厂实现类
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建临时文件目录
            File tempPath = new File("D://abc");
            //设置临时文件存放的路径
            fileItemFactory.setRepository(tempPath);
            //设置缓冲区大小
            fileItemFactory.setSizeThreshold(10240);
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //解决上传文件名乱码
            servletFileUpload.setHeaderEncoding("UTF-8");
            try {
                //解析上传的数据，得到每一个表单项
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                String dishName = null;
                float price = 0F;
                String describe = null;
                int storeId = 0;
                //循环判断每一表单项是普通类型，还是文件类型
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        //普通表单项
                        if ("storeId".equals(fileItem.getFieldName())) {
                            storeId = Integer.parseInt(fileItem.getString());
                        }
                        if ("dishName".equals(fileItem.getFieldName())) {
                            dishName = fileItem.getString("UTF-8");
                        }
                        if ("price".equals(fileItem.getFieldName())) {
                            price = Float.parseFloat(fileItem.getString("UTF-8"));
                        }
                        if ("describe".equals(fileItem.getFieldName())) {
                            describe = fileItem.getString("UTF-8");
                        }
                    } else {
                        //上传的图片，获取到文件名
                        String fileItemName = fileItem.getName();
                        if (fileItemName != null && !"".equals(fileItemName)) {
                            String str = fileItemName.substring(fileItemName.lastIndexOf(".") + 1);
                            //判断图片类型
                            if ("png".equals(str) || "jpg".equals(str)) {
                                //获取文件上传的文件输入流
                                InputStream inputStream = fileItem.getInputStream();
                                int id = dishService.addDish(dishName, storeId, price, describe);
                                if (id > 0) {
                                    //创建一个文件输出流
                                    FileOutputStream out = new FileOutputStream(uploadFilePath + "/" + id + "." + str);
                                    //创建一个缓冲区
                                    byte[] buffer = new byte[1024];
                                    //判断输入流中的数据是否已经读完的标识
                                    int len;
                                    //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
                                    while ((len = inputStream.read(buffer)) > 0) {
                                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录当中
                                        out.write(buffer, 0, len);
                                    }
                                    //关闭输入流
                                    inputStream.close();
                                    //关闭输入流
                                    out.flush();
                                    out.close();
                                    //删除处理文件上传时生成的临时文件
                                    fileItem.delete();
                                    resp.sendRedirect("/Seller/SellerDishPage.jsp?storeId=" + storeId);
                                }
                            } else {
                                resp.sendRedirect("/Seller/AddDish.jsp?storeId=" + storeId);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

